package com.ky.serialport.sensor;

import com.ky.serialport.bean.ComBean;
import com.ky.serialport.utils.MyFunc;

import static com.ky.serialport.utils.RandomUtils.myRandom;

/**
 * 压力传感器数据解析
 */
public class YaLiDataBean {
    public Long time = 0L;
    public int index = -1; //传感器序号
    public int type = 0; //传感器类型
    public int power = 0; //电量
    public int signal = 0; //信号
    public Float[] yaLiArray = new Float[5]; //压力数据
    public float yaLiVel = 0F; //平均压力
    public ComBean comBean;

    public YaLiDataBean() {
    }

    public YaLiDataBean(ComBean comBean) {
        caculate(comBean.recData);
        time = comBean.recTime;
    }

    public YaLiDataBean(byte[] recData) {
        caculate(recData);
        time = System.currentTimeMillis();
    }

    public YaLiDataBean caculate(ComBean comBean){
        this.comBean = comBean;
        time = comBean.recTime;
        return caculate(comBean.recData);
    }

    public YaLiDataBean caculate(byte[] bRec ) {

        time = System.currentTimeMillis();
        type = bRec[9];
        index = bRec[10];
        power = MyFunc.getPower(bRec[29],bRec[30]);
        signal = MyFunc.getSignal(bRec[31]); //测试信号

        float fraction = 1f;
        // TODO: 2020/2/17 需要核实，协议有可能不对
        switch (type){
            case 32: //0x20
            case 33: //0x21
            case 35: //0x23
            case 36: //0x24
                fraction = 1000f;
                break;
            case 39: //0x27
                fraction = 10f;
                break;
        }

        int symbol0 = bRec[14];
        int symbol1 = bRec[17];
        int symbol2 = bRec[20];
        int symbol3 = bRec[23];
        int symbol4 = bRec[26];

        yaLiArray[0] = MyFunc.twoByte2IntNoSign(bRec[15],bRec[16]) / fraction;
        yaLiArray[1] = MyFunc.twoByte2IntNoSign(bRec[18],bRec[19]) / fraction;
        yaLiArray[2] = MyFunc.twoByte2IntNoSign(bRec[21],bRec[22]) / fraction;
        yaLiArray[3] = MyFunc.twoByte2IntNoSign(bRec[24],bRec[25]) / fraction;
        yaLiArray[4] = MyFunc.twoByte2IntNoSign(bRec[27],bRec[28]) / fraction;

        if (symbol0 == 1)  yaLiArray[0] = 0 -  yaLiArray[0];
        if (symbol1 == 1)  yaLiArray[1] = 0 -  yaLiArray[1];
        if (symbol2 == 1)  yaLiArray[2] = 0 -  yaLiArray[2];
        if (symbol3 == 1)  yaLiArray[3] = 0 -  yaLiArray[3];
        if (symbol4 == 1)  yaLiArray[4] = 0 -  yaLiArray[4];

        yaLiVel =  (yaLiArray[0] + yaLiArray[1] + yaLiArray[2] + yaLiArray[3] + yaLiArray[4]) / 5f;
        return this;
    }

    public YaLiDataBean test(int index) {
        time = System.currentTimeMillis();
        this.index = index;
        power = 300 + myRandom.nextInt(120);
        signal = 200;
        yaLiVel = 20 * myRandom.nextFloat();
        return this;
    }

}
